package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import entity.User;
import util.Constants;
import util.Validator;

public class AddUserJPanel extends JPanel {
	private static final long serialVersionUID = 8549141458642551032L;

	public AddUserJPanel(){
        setLayout(null);
        initUI();
	}
	
	private void initUI(){
		JLabel lab1 = new JLabel("用户名",SwingConstants.RIGHT);
		lab1.setFont(Constants.font);
		lab1.setBounds(100, 30, 60, 30);
	        
        JTextField lab1input = new JTextField();
        lab1input.enableInputMethods(false);
        lab1input.setBounds(165, 30, 120, 30);
        
        JLabel lab2 = new JLabel("类型",SwingConstants.RIGHT);
        lab2.setFont(Constants.font);
        lab2.setBounds(100, 90, 60, 30);
        
        JComboBox<String> lab2input = new JComboBox<>();
        lab2input.addItem("-请选择-");
        lab2input.addItem(Constants.gate);
        lab2input.addItem(Constants.manager);
        lab2input.setBounds(165, 90, 120, 30);
        
		JLabel lab3 = new JLabel("备注",SwingConstants.RIGHT);
		lab3.setFont(Constants.font);
		lab3.setBounds(100, 150, 60, 30);
		
		JTextField lab3input = new JTextField();
		lab3input.setBounds(165, 150, 120, 30);
        
		JButton btn = new JButton("保存");
		btn.setBounds(165, 210, 60, 30);
		btn.setFont(Constants.font);
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String lab1inputStr = lab1input.getText().trim();
				String lab2inputStr = lab2input.getSelectedItem().toString();
				String lab3inputStr = lab3input.getText().trim();

				if (Validator.isEmpty(lab1inputStr)) {
					JOptionPane.showMessageDialog(null, "请输入用户名！");
					return;
				}
				
				if (lab2input.getSelectedIndex() < 1) {
					JOptionPane.showMessageDialog(null, "请输入类型！");
					return;
				}

				boolean result = false;
				User user = new User();
				user.name = lab1inputStr;
				user.pwd = "123456";
				user.type = lab2inputStr;
				user.note = lab3inputStr;

				result = user.save();
				if (result) {
					JOptionPane.showMessageDialog(null, "操作成功！");
				}else{
					JOptionPane.showMessageDialog(null, "操作失败！");
				}
			}
				
		});
		
		add(lab1);
		add(lab1input);
		add(lab2);
		add(lab2input);
		add(lab3);
		add(lab3input);
		add(btn);
	}
}
